//
//  NetworkError.swift
//  Kosspot
//
//  Created by 胡辉 on 2025/6/29.
//

import Foundation


enum NetworkError: Error, LocalizedError {
    case invalidURL
    case requestFailed(description: String)
    case invalidResponse(statusCode: Int)
    case decodingFailed
    case unauthorized
    case serverError(code: Int, message: String)
    case missingRequiredField(field: String)
    
    var errorDescription: String? {
        switch self {
        case .invalidURL:
            return "无效的URL"
        case .requestFailed(let desc):
            return "请求失败: \(desc)"
        case .invalidResponse(let code):
            return "服务器错误(状态码: \(code))"
        case .decodingFailed:
            return "数据解析失败"
        case .unauthorized:
            return "登录已过期，请重新登录"
        case .serverError(let code, let message):
            return message
        case .missingRequiredField(let field):
            return "缺少必要字段: \(field)"
        }
    }
    
    var code: Int? {
        if case .serverError(let code, _) = self {
            return code
        }
        return nil
    }
    
    var isAuthenticationError: Bool {
        return code == 401 || code == 403
    }
}
